package com.wbao.dianniu.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.powerfulrecyclerview.listener.OnRefreshListener;
import com.powerfulrecyclerview.ptr.HistoryThemeHeaderView;
import com.powerfulrecyclerview.ptr.PowerfulRecyclerView;
import com.powerfulrecyclerview.ptr.SimDividerItemDecoration;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.QAInfoAdapter;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.listener.IQaListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.QaManager;
import com.wbao.dianniu.manager.QuestDelManager;
import com.wbao.dianniu.manager.QuestGoodManager;
import com.wbao.dianniu.update.QaDataChangeManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.PictureDownloadUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的收藏
 * <p>
 * Created by yejianjun on 2018/11/10.
 */
public class CollectQaFragment extends Fragment implements IQaListener, View.OnClickListener, QaDataChangeManager.IQaDataListener, OnRefreshListener, QAInfoAdapter.OnItemClickListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;

    private QaManager manager;
    private QaDataChangeManager qaDataChangeManager;

    private QAInfoAdapter adapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private static Context mContext;
    private TextView noDataTV;
    private PowerfulRecyclerView recyclerView;
    private HistoryThemeHeaderView header;
    // 是否上拉加载更多
    private int lastVisibleItem = 0;
    private final int PAGE_COUNTS = 10;
    private int default_type = 5;
//    private List<QaResponse> mList;


    public static CollectQaFragment instance(Context context) {
        mContext = context;
        CollectQaFragment view = new CollectQaFragment();
        return view;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_my_collection, null);
        initManager();

        adapter = new QAInfoAdapter(getContext());
        adapter.setOnItemClickListener(this);
        adapter.changeMoreStatus(QAInfoAdapter.PULLUP_LOAD_MORE);

        initView(view);
//        initWattingView(view);
        initLoadMoreListener();
        requestData();
        return view;
    }

    private void initManager() {
        manager = new QaManager(getContext());
        manager.addQaListener(this);
        qaDataChangeManager = QaDataChangeManager.getInstance();
        qaDataChangeManager.addQaChangeListener(this);
        mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
    }

    private void initView(View view) {
        noDataTV = view.findViewById(R.id.no_find_data);

        recyclerView = view.findViewById(R.id.collectionListView);
        recyclerView.setAdapter(adapter);
        // 设置布局管理器
        recyclerView.setLayoutManager(mLayoutManager);
        // 设置分割线
        recyclerView.addItemDecoration(new SimDividerItemDecoration(getContext()));
        // 设置adapter
        header = (HistoryThemeHeaderView) LayoutInflater.from(getContext()).inflate(R.layout.history_header_theme, recyclerView, false);
        recyclerView.setHeaderView(header);
        recyclerView.setLoadMoreEnable(false);
        recyclerView.setRefreshEnable(false);
        recyclerView.setOnRefreshListener(this);
    }

    private void initWattingView(View view) {
        waittingLayout = view.findViewById(R.id.waitting_layout);
        waittingProBar = view.findViewById(R.id.waitting_progress);
        waittingTV = view.findViewById(R.id.waitting_text_desc);
    }

    /**
     * 上拉加载更多
     */
    private void initLoadMoreListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                    //设置正在加载更多
                    adapter.changeMoreStatus(QAInfoAdapter.LOADING_MORE);
                    // 上拉刷新 加载请求数据
                    pullUpRequest();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }

    // 上拉刷新数据请求
    private void pullUpRequest() {
        // 没有搜索结果 或者数据为空 上拉没有效果
        reqData("up");
    }

    private void requestData() {
        reqData("down");
    }

    private void reqData(String refresh) {
        manager.reqData(GlobalContext.getAccountId(), "", default_type, 0, PAGE_COUNTS, adapter.getLastId(), refresh);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onQaFailure(int errorCode, String errorMsg) {
        recyclerView.stopRefresh();
        adapter.changeMoreStatus(QAInfoAdapter.NO_LOAD_MORE);
    }

    @Override
    public void onQaSuccess(List<QaResponse> list) {
        recyclerView.stopRefresh();
        if (null != list) {
            adapter.addBackwardList(list);
            if (adapter.getList().size() == 0) {
                noDataTV.setVisibility(View.VISIBLE);
            } else {
                noDataTV.setVisibility(View.GONE);
            }
        }
        adapter.changeMoreStatus(QAInfoAdapter.NO_LOAD_MORE);
    }

    @Override
    public void addOneData(QaResponse addData) {
        noDataTV.setVisibility(View.GONE);
        adapter.addOneQuestData(addData);
//        mList = adapter.getList();
    }

    @Override
    public void removeOneData(int questId) {
        adapter.removeOneData(questId);
//        mList = adapter.getList();
        if (adapter.getList().size() == 0) {
            noDataTV.setVisibility(View.VISIBLE);
        } else {
            noDataTV.setVisibility(View.GONE);
        }
    }

    @Override
    public void priseNotify(int questId, int isGood, int goodCounts) {
        adapter.priseNotify(questId, isGood, goodCounts);
    }

    @Override
    public void replyNotify(int questId, int answerCounts) {
        adapter.replyNotify(questId, answerCounts);
    }

    @Override
    public void visitorUpdate(int questId, int visitorCounts) {
        adapter.visitorUpdate(questId, visitorCounts);
    }

    @Override
    public void itemClick(View v) {
        final int position;
        QaResponse resp;
        switch (v.getId()) {
            case R.id.qa_item_layout:
                position = (Integer) v.getTag(R.id.qa_item_layout);
                ActivityUtils.intoQaDetailActivity(getContext(), adapter.getList().get(position));
                break;
            case R.id.user_head:
                position = (Integer) v.getTag(R.id.user_head);
                resp = adapter.getList().get(position);
                ActivityUtils.intoHeadInfoActivity(resp.accountId, getContext());
                break;
            case R.id.user_name:
                position = (Integer) v.getTag(R.id.user_name);
                resp = adapter.getList().get(position);
                ActivityUtils.intoHeadInfoActivity(resp.accountId, getContext());
                break;
            case R.id.qa_content_tv:
                position = (Integer) v.getTag(R.id.qa_content_tv);
                resp = adapter.getList().get(position);
                ActivityUtils.intoQaDetailActivity(getContext(), resp);
                break;
            case R.id.include_answer_tv:
                position = (Integer) v.getTag(R.id.include_answer_tv);
                resp = adapter.getList().get(position);
                ActivityUtils.intoQaDetailActivity(getContext(), resp);
                break;
            case R.id.include_forward_tv:
                String imageUrl = null;
                position = (Integer) v.getTag(R.id.include_forward_tv);
                resp = adapter.getList().get(position);
                if (TextUtils.isEmpty(resp.questImgs)) {
                    imageUrl = GlobalContext.cdndownUrl + resp.userInfo.headPic;
                } else {
                    ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
                    imageUrl = imageUrls.get(0);
                }
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(getContext(), resp.content, 1, imageUrl, resp.id);
                break;
            case R.id.include_praise_tv:
                position = (Integer) v.getTag(R.id.include_praise_tv);
                resp = adapter.getList().get(position);
                if (resp.isGood == 0) {
                    resp.isGood = 1;
                    resp.goodCount++;
                } else {
                    resp.isGood = 0;
                    resp.goodCount--;
                }
                QaDataChangeManager qaDataChangeManager = QaDataChangeManager.getInstance();
                qaDataChangeManager.priseNotify(adapter.getList().get(position).id, resp.isGood, resp.goodCount);
                goodclick(adapter.getList().get(position).id);
                break;
            case R.id.include_delete_tv:
                // 删除传入的参数是Id
                position = (Integer) v.getTag(R.id.include_delete_tv);
                CustomDialog.Builder builder = new CustomDialog.Builder(getContext());
                builder.setTitle("确认删除该条问答吗？");
                builder.setPositiveButton(getResources().getString(R.string.confirm),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                QuestDelManager questDelManager = new QuestDelManager(getContext());
                                questDelManager.deleteQuest(GlobalContext.getAccountId(), position);
                                QaDataChangeManager manager = QaDataChangeManager.getInstance();
                                manager.notifyRemove(position);
                            }
                        });
                builder.setNegativeButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeQaListener(this);
        }
        if (null != qaDataChangeManager) {
            qaDataChangeManager.removeQaChangeListener(this);
        }
    }

    private void goodclick(int questId) {
        QuestGoodManager manager = new QuestGoodManager(getContext());
        manager.good(GlobalContext.getAccountId(), questId);
    }

}
